package com.vogue.api.common.redisson;


import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

/**
 * redisson操作类
 */
@Service("redissonService")
public class RedissonService {

    @Autowired
    private RedissonClient redissonClient;

    public void set(String key, Object value) {
        redissonClient.getBucket(key, JsonJacksonCodec.INSTANCE).set(value);
    }

    /**
     * 带过期时间
     * @param key
     * @param value
     * @param expire
     */
    public void setExpire(String key, Object value,Long expire) {
        redissonClient.getBucket(key, JsonJacksonCodec.INSTANCE).set(value,expire,TimeUnit.SECONDS);
    }

    public void delete(String key) {
        redissonClient.getBucket(key, JsonJacksonCodec.INSTANCE).delete();
    }

    /**
     * 获取短信验证码
     * @param mobile
     * @return
     */
    public String getSmsCode(String mobile){
        String key = String.format(RedisConstant.UserSmsCode, mobile);
        RBucket<String> bucket = this.redissonClient.getBucket(key, JsonJacksonCodec.INSTANCE);
        return (String) bucket.get();
    }
    /**
     * 通过token获取UserID
     * @param token
     * @return
     */
    public String getUserIdByToken(String token) {
        String key = String.format(RedisConstant.UserIdByToken, token);
        RBucket<String> bucket = this.redissonClient.getBucket(key, JsonJacksonCodec.INSTANCE);
        return (String) bucket.get();
    }

    /**
     * 通过UserID获取用户信息
     * @param userId
     * @return
     */
    public String getUserInfoByUserId(String userId) {
        String key = String.format(RedisConstant.UserInfoByUserId, userId);
        RBucket<String> bucket = this.redissonClient.getBucket(key, JsonJacksonCodec.INSTANCE);
        return (String) bucket.get();
    }




}
